# _*_ coding:utf-8 _*_
# @Time  : 2023.06.08
# @Author: zizlee
import pathlib
import datetime
from enum import Enum
from fastapi import APIRouter, Form, UploadFile
from response import APIResponse
from utils import file_utils
from settings import STATIC_HOST


image_api = APIRouter()


class ImageScopeEnum(Enum):
    AVATAR = 'avatar'
    SUGGEST = 'suggest'


@image_api.post('/upload/')
async def upload_image(scope: ImageScopeEnum = Form(...), image: UploadFile = Form(...)):
    if scope.value == scope.AVATAR.value:
        file_folder = f'image/{scope.value}/'
    else:
        file_folder = f'image/{scope.value}/{datetime.date.today().strftime("%Y-%m")}/'
    fileinfo = file_utils.generate_unique_fileinfo(file_folder=file_folder,
                                                   filename=image.filename,
                                                   suffix=pathlib.Path(image.filename).suffix,
                                                   hashed=True)
    # print(fileinfo)
    # 保存文件
    with open(fileinfo['filepath'], 'wb') as fp:
        content = await image.read()
        fp.write(content)
    image_url = STATIC_HOST + fileinfo['folder'] + fileinfo['filename'] + fileinfo['suffix']
    return APIResponse.success(data={'image_url': image_url})
